//首先,我们在src目录下创建request文件夹,里面创建一个axios.js文件
import axios from 'axios';
import {
    Message,
	MessageBox,
	Loading
} from 'element-ui'
import Router from '@/router/index'


let loading, loadCount = 0,loadingArray=[];
function startLoading() {
  loadCount++
  loading = Loading.service({
    lock: true,
    text: "拼命加载中...",
    target: document.querySelector('.content')//设置加载动画区域
  });
  loadingArray.push(loading)
}
function endLoading() {
	loadCount--
	if (!loadCount) {
	 loadingArray.forEach(item=>item.close())
  }
}


// axios.defaults.timeout = 5000;
//request请求拦截器
axios.interceptors.request.use(
	config => {
		startLoading()
		config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
		return config;
	},
	error => {
		return Promise.reject(error)
	}
)

//response响应拦截器
axios.interceptors.response.use(
	response => {
		endLoading()
		if(response.data.code == 200){
			return Promise.resolve(response.data)
		}else if(response.data.code == undefined){
			return Promise.resolve(response)
		}else if(response.data.code == '600005'){
			MessageBox(response.data.msg, '提示', {
				confirmButtonText: '确定',
				callback: action => {
				}
			});
			return Promise.resolve("");
		}else{
			MessageBox(response.data.msg, '提示', {
				confirmButtonText: '确定',
				callback: action => {
				}
			});
			return Promise.resolve("");
		}
	},
	error => {
		endLoading()
		if(error.response.status == 401){
			return Promise.reject(error);
		}
		if(error.response.data.code == '040005'){
			MessageBox("登录过期", '提示', {
				confirmButtonText: '确定',
				callback: action => {
				}
			});
			Router.push('/');
		}else{
			MessageBox("请求失败", '提示', {
				confirmButtonText: '确定',
				callback: action => {
				}
			});
		}
		return Promise.reject(error);
		
	}
)
export default axios;
